﻿using System;
using System.Web;
using System.Web.UI;

namespace JQuery.WebKit.WebCommon.Theming
{
    public class ThemeSwitcherModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(System.Web.HttpApplication context)
        {
            context.PreRequestHandlerExecute += PreRequestHandlerExecute;
        }

        protected void PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpContext currentContext = HttpContext.Current;
            if (!(currentContext.Handler is Page))
            {
                return;
            }
            Page currentPage = currentContext.Handler as Page;

            if (currentPage != null)
            {
                HttpCookie cookie = currentContext.Request.Cookies[CookieName()];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                {
                    if (ThemeExists(cookie.Value))
                    {
                        currentPage.Theme = cookie.Value;
                    }
                    cookie.Expires = DateTime.Today.AddDays(90);
                }
                else
                {
                    //no theme available, get the default one
                    Theme theme = ThemeManager.GetDefaultTheme();
                    if (theme != null)
                    {
                        currentPage.Theme = theme.Name;
                    }
                }
            }
        }

        private bool ThemeExists(string theme)
        {
            return System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/App_Themes/" + theme));
        }

        private string CookieName()
        {
            // name for the cookie that is different for each application
            string Path = HttpContext.Current.Request.ApplicationPath;
            return Path.Substring(1, Path.Length - 1) + "_tsTheme";
        }

    }

}
